<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/html">
<head>
    <th:block th:include="include :: header('新增datax')" />
    <th:block th:include="include :: datetimepicker-css" />
    <th:block th:include="include :: jquery-smartwizard-css" />
    <th:block th:include="include :: select2-css" />
    <style type="text/css">
        /* 如果要让工具栏固定在页面底部,使用下面的样式,不需要的可以注释 */
        .sw>.toolbar-bottom{
            z-index: 100;
            bottom: 0px;
            left: 0;
            width: 100%;
            position: fixed;
            text-align: right;
            background: #fff;
            box-shadow: 0 -2px 6px 1px hsla(223,8%,83%,.5);
            border-top: 1px solid #e3e4e8;
        }
        /* 如果设置了是否自动调节高度为false,需要加滚动条 */
        .sw>.tab-content{
            overflow-x: hidden;
            overflow-y: auto;
        }
        /* 解决工具栏无法固定底部的问题（如果页面没有animated类可以不写这部分代码） */
        .animated {
            animation-fill-mode: none;
            -webkit-animation-fill-mode: none;
            -moz-animation-fill-mode: none;
            -o-animation-fill-mode: none;
        }
        input:checked {

        }
    </style>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight" style="height: 100%;">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox">
                <div class="ibox-title" style="margin: 0;padding: 5px 0 0 0">
                    <form class="form form-horizontal m-t" style="margin: 0;padding: 0">
                        <div class="form-group" style="width: 700px;padding: 0;margin: 0">
                            <label class="col-sm-2 control-label">源数据库：</label>
                            <div class="col-sm-4">
                                <select name="idDb" id="idDb" style="margin-bottom: 5px" class="form-control m-b" th:with="type=${@baseDbService.selectAll()}" onchange="dbChange()">
                                    <option th:each="item : ${type}" th:text="${item.na}" th:value="${item.idDb}" th:attr="cd=${item.cd}" th:if="${item.sdBuscls!='dw'}"></option>
                                </select>
                            </div>
                            <label class="col-sm-2 control-label">目标库：</label>
                            <div class="col-sm-4">
                                <select name="idDb" id="dwIdDb" disabled style="margin-bottom: 5px" class="form-control m-b" th:with="type=${@baseDbService.selectAll()}" onchange="dbChange()">
                                    <option th:each="item : ${type}" th:text="${item.na}" th:value="${item.idDb}" th:if="${item.sdBuscls=='dw'}"></option>
                                </select>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="ibox-content">
                    <div id="smartwizard">
                        <ul class="nav">
                            <li class="nav-item">
                                <a class="nav-link" href="#step-1"> 第一步 </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="#step-2"> 第二步 </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="#step-3"> 第三步 </a>
                            </li>
                        </ul>
                        <div class="tab-content">
                            <div id="step-1" class="tab-pane" role="tabpanel" aria-labelledby="step-1" style="min-height: 500px">
                                <div>
                                    <form class="form form-horizontal m-t">
                                        <div class="form-group" >
                                            <label class="col-sm-2 control-label">表名：</label>
                                            <!--<div class="col-sm-4" >
                                                <select class="form-control" id="tableSelect" onchange="tableChange()"></select>
                                            </div>-->
                                            <div class="col-sm-4" >
                                                <input type="text" class="form-control" id="tableSelect" />
                                            </div>
                                            <div class="col-sm-4">
                                                <button type="button" class="btn btn-info btn-sm" onclick="sourceFldRefresh()">获取列</button>
                                                <button type="button" class="btn btn-primary btn-sm" onclick="showCreSQl()">建表SQL</button>
                                            </div>
                                        </div>
                                        <div class="form-group" >
                                            <label class="col-sm-2 control-label">表描述：</label>
                                            <div class="col-sm-4" >
                                                <input class="form-control" id="tableName"/>
                                            </div>
                                        </div>
                                        <div class="form-group" >
                                            <label class="col-sm-2 control-label">表分类：</label>
                                            <div class="col-sm-4" >
                                                <select name="sdOdsCls" id="sdOdsCls" class="form-control" th:with="type=${@baseSd.getItem('draw_ods_cls')}">
                                                    <option th:each="item : ${type}" th:text="${item.na}" th:value="${item.cd}"></option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="form-group" >
                                            <label class="col-sm-2 control-label">切分字段：</label>
                                            <div class="col-sm-4" >
                                                <input class="form-control" id="splitPk"/>
                                            </div>
                                        </div>
                                        <div class="form-group" >
                                            <label class="col-sm-2 control-label">查询语句：</label>
                                            <div class="col-sm-5" >
                                                <textarea class="form-control" rows="5" id="qrySql"></textarea>
                                            </div>
                                            <div class="col-sm-4">
                                                <button type="button" class="btn btn-info btn-sm" onclick="sourceFldRefresh()">获取列</button>
                                            </div>
                                        </div>
                                        <div class="form-group" >
                                            <label class="col-sm-2 control-label">过滤条件：</label>
                                            <div class="col-sm-5" id="radiosDiv">
                                                <div class="radio check-box">
                                                    <label>
                                                        <input type="radio" id="selfWhere" value="self" checked name="whereRadio" onchange="radioChange(this)"> <i></i>自定义</label>
                                                </div>
                                                <div class="radio check-box">
                                                    <label>
                                                        <input type="radio" value="all" name="whereRadio" onchange="radioChange(this)"> <i></i>全部</label>
                                                </div>
                                                <div class="radio check-box">
                                                    <label>
                                                        <input type="radio" value="dt" name="whereRadio" onchange="radioChange(this)"> <i></i> 日期</label>
                                                </div>
                                            </div>
                                            <div class="col-sm-5"></div>
                                        </div>
                                        <div class="form-group" id="dtFld" style="display: none">
                                            <label class="col-sm-2 control-label"></label>
                                            <div class="col-sm-5" >
                                                <select class="form-control" id="dtFldSelect" placeholder="请输入日期字段"></select>
                                            </div>
                                            <div class="col-sm-5"></div>
                                        </div>
                                        <div class="form-group" id="whereSql" >
                                            <label class="col-sm-2 control-label"></label>
                                            <div class="col-sm-5" >
                                                <textarea class="form-control" rows="5" placeholder="过滤SQL" id="whereSqlArea"></textarea>
                                            </div>
                                            <div class="col-sm-5"></div>
                                        </div>
                                        <div class="form-group" >
                                            <label class="col-sm-2 control-label">源字段：</label>
                                            <div class="col-sm-5" >
                                                <div class="col-sm-12" id="sourFldCheckBoxDiv" ></div>
                                            </div>
                                            <div class="col-sm-4">
                                                <button type="button" class="btn btn-info btn-sm" onclick="sourceFldRefresh()">刷新</button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                            <div id="step-2" class="tab-pane" role="tabpanel" aria-labelledby="step-2">
                                <div>
                                    <form class="form form-horizontal m-t">
                                        <div class="form-group" >
                                            <label class="col-sm-2 control-label">目标表：</label>
                                            <div class="col-sm-3" >
                                                <input type="text" id="tableTar" class="form-control" disabled/>
                                            </div>
                                            <div class="col-sm-7"></div>
                                        </div>
                                        <div class="form-group" >
                                            <label class="col-sm-2 control-label">前置sql：</label>
                                            <div class="col-sm-5" >
                                                <textarea class="form-control" rows="5" id="prefixSql"></textarea>
                                            </div>
                                            <div class="col-sm-5"></div>
                                        </div>
                                        <div class="form-group" >
                                            <label class="col-sm-2 control-label">字段：</label>
                                            <div class="col-sm-5" >
                                                <div class="col-sm-12" id="fldCheckBoxDiv" ></div>
                                            </div>
                                            <div class="col-sm-5"></div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                            <div id="step-3" class="tab-pane" role="tabpanel" aria-labelledby="step-3">
                                <div class="ibox float-e-margins">
                                    <div class="ibox-title">
                                        <h5>DATAX模板</h5>
                                    </div>
                                    <div class="ibox-content">
                                        <pre id="dataxJson"></pre>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>

<div class="modal inmodal fade" id="myModal5" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
                </button>
                <h4 class="modal-title">表创建语句</h4>
            </div>
            <div class="modal-body">
                <textarea id="creSql" style="width: 100%;" rows="10"></textarea>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="copyTableCreSql()">复制</button>
                <button type="button" class="btn btn-danger" onclick="execSql()">执行</button>
            </div>
        </div>
    </div>
</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: datetimepicker-js" />
<th:block th:include="include :: jquery-smartwizard-js" />
<th:block th:include="include :: select2-js" />
<script th:inline="javascript">
    var prefix = ctx + "etl/datax";
    var SOURCE_TABLE_FIELDS=[];
    $(document).ready(function() {
        $("#prefix").keyup(function (event) {
            if(event.keyCode==13) {
                filterTables();
            }
        });
        dbChange();
        // 工具栏按钮
        var btnFinish = $('<a id="btn-finish"></a>').text('完成')
            .addClass('btn btn-info')
            .on('click', function(){ submit(); });
        var btnCancel = $('<a id="btn-cancel"></a>').text('取消')
            .addClass('btn btn-danger')
            .on('click', function(){ $('#smartwizard').smartWizard("reset"); });
        // 下面两个按钮是为了因为插件默认的是botton,这里换成<a>,也可以选择用样式替换,或者不替换
        var btnNext = $('<a id="btn-next"></a>').text('下一步')
            .addClass('btn btn-info')
            .on('click', function(){ $('#smartwizard').smartWizard("next");});
        var btnPrev = $('<a id="btn-prev"></a>').text('上一步')
            .addClass('btn btn-success disabled')
            .on('click', function(){ $('#smartwizard').smartWizard("prev"); });
        // 初始化表单向导组件
        $('#smartwizard').smartWizard({
            theme: 'arrows', // default, arrows, dots, progress
            autoAdjustHeight : false, // 自动调整高度, 默认true
            enableURLhash:false, //开启URL hash,开启后点击浏览器前进后退按钮会执行下一步和上一步操作
            transition: {
                animation: 'slide-horizontal', // Effect on navigation, none/fade/slide-horizontal/slide-vertical/slide-swing
            },
            toolbarSettings: {
                showNextButton: false,// 因为上面自定义了下一步按钮, 所以隐藏掉插件自带的按钮, 如果不使用自定义按钮, 需要改为true或者去掉该属性
                showPreviousButton: false,// 因为上面自定义了上一步按钮, 所以隐藏掉插件自带的按钮, 如果不使用自定义按钮, 需要改为true或者去掉该属性
                toolbarExtraButtons: [btnCancel,btnPrev,btnNext,btnFinish]// 扩展的按钮集合
            }
        });
    });
    var sourceFldRefresh = function () {
        $.ajax({
            url: ctx+"base/etl/table/query/columns",
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify({"tableName":$("#tableSelect").val(),"idDb":$("#idDb").val(),"qrySql":$("#qrySql").val()}),
            contentType: 'application/json;charset=UTF-8',
            success: function (result) {
                if(result.code==0) {
                    debugger;
                    var data = result.data;
                    var options="",html="";
                    SOURCE_TABLE_FIELDS = data;
                    $.each(data,function (index,t) {
                        if(t.type==91 || t.type==92 || t.type==93) {
                            options += "<option>"+t.name+"</option>";
                        }
                        html += "<label class=\"checkbox-inline\"><input type=\"checkbox\" checked disabled value=\""+t.name+"\" >"+t.name+"</label>";
                    });
                    $("#dtFldSelect").html(options);
                    $("#sourFldCheckBoxDiv").html(html);
                } else {
                    $.modal.alertError(result.msg);
                }
            }
        });
        $("#sourFldCheckBoxDiv").html();
    };
    function showCreSQl() {
        var cdSys = $("#idDb").find("option:checked").attr("cd");
        $.ajax({
            url: ctx+"base/etl/table/generateCreateTableSql",
            async: false,
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify({"newTablePrefix":"ods_"+cdSys+"_"+$("#sdOdsCls").val()+"_","tableName":$("#tableSelect").val(),"idDb":$("#idDb").val(),"qrySql":$("#qrySql").val()}),
            contentType: 'application/json;charset=UTF-8',
            success: function (result) {
                if(result.code==0) {
                    $("#creSql").html(result.data);
                    $("#myModal5").modal("show");
                } else {
                    $.modal.alertError("表不存在");
                }
            }
        });
    };
    function execSql() {
        var sql = $("#creSql").val();
        if(sql.indexOf("create table ")>-1) {
            $.ajax({
                url: ctx+"base/etl/table/execSql",
                type: 'POST',
                dataType: 'json',
                data: JSON.stringify({"sqlCreat":$("#creSql").val()}),
                contentType: 'application/json;charset=UTF-8',
                success: function (result) {
                    if(result.code==0) {
                        $.modal.alertSuccess(result.msg);
                    } else {
                        $.modal.alertError(result.msg);
                    }
                }
            });
        } else {
            $.modal.alertWarning("请先生成建表语句");
        }
    }
    function copyTableCreSql() {
        $("#creSql").focus();
        $("#creSql").select();
        document.execCommand("copy");
        $.modal.msgSuccess("复制成功");
    }
    //表变化时过滤条件恢复原样
    function tableChange() {
        $("#dtFldSelect").html("");
        $("#whereSqlArea").val("");
        radioChange();
    }
    function radioChange() {
        var type = $("#radiosDiv").find("input[type='radio']:checked").val();
        if(type=="") {
            return;
        }
        if(type=="dt") {
            $("#dtFld").show();
            $("#whereSql").hide();
        }else if(type=="all") {
            $("#dtFld").hide();
            $("#whereSql").hide();
        } else if(type=="self") {
            $("#dtFld").hide();
            $("#whereSql").show();
        }
    }
    function submit(){
        var whereType = $("#radiosDiv").find("input:checked").val();
        var data = {"sdOdsCls":$("#sdOdsCls").val(),"tbSour":$("#tableSelect").val(),"tbTar":$("#tableTar").val(),"na":$("#tableName").val(),"idDb":$("#idDb").val(),"config":$("#dataxJson").text(),"euWhereType":whereType,"fldDt":$("#dtFldSelect").val()};
        $.ajax({
            url: ctx + "base/etl/datax/add",
            async: false,
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify(data),
            contentType: 'application/json;charset=UTF-8',
            success: function (result) {
                if(result.code==0) {
                    $.modal.alertSuccess("添加成功，记得刷新列表查看")
                     $.modal.close();
                } else {
                    $.modal.alertError(result.msg);
                }
            }
        });
    }
    // 显示步骤时将触发事件
    $("#smartwizard").on("showStep", function(e, anchorObject, stepNumber, stepDirection, stepPosition) {
        // 下面按钮是快速操作栏的
        $("#prev-btn").removeClass('disabled');
        $("#next-btn").removeClass('disabled');
        // 下面按钮是工具栏的
        $("#btn-prev").removeClass('disabled');
        $("#btn-next").removeClass('disabled');
        $("#btn-finish").removeClass('disabled');
        if(stepPosition === 'first') {
            $("#prev-btn").addClass('disabled');// 快速操作栏（演示用）
            $("#btn-prev").addClass('disabled');
            $("#btn-finish").addClass('disabled');
        } else if(stepPosition === 'last') {
            $("#next-btn").addClass('disabled');// 快速操作栏（演示用）
            $("#btn-next").addClass('disabled');
        } else {
            $("#prev-btn").removeClass('disabled');// 快速操作栏（演示用）
            $("#next-btn").removeClass('disabled');// 快速操作栏（演示用）
            $("#btn-prev").removeClass('disabled');
            $("#btn-next").removeClass('disabled');
            $("#btn-finish").addClass('disabled');
        }
    });

    // 该事件在离开某个步骤之前触发
    $("#smartwizard").on("leaveStep", function(e, anchorObject, currentStepNumber, nextStepNumber, stepDirection) {
        if(stepDirection == 'forward' && nextStepNumber==1){
            var tablename = $("#tableSelect").val();
            if(tablename=="") {
                $.modal.alertError("至少选择一个表");
                return false;
            } else {
                // 与ods_系统_表配置的
                var sourCheckBox="",tarCheckBox="",invaCheckBox="";
                var cdSys = $("#idDb").find("option:checked").attr("cd");
                var sdOdsCls = $("#sdOdsCls").val();
                let odsTable = "ods_"+cdSys+"_"+sdOdsCls+"_"+tablename.toLowerCase();
                $("#tableTar").val(odsTable);
                if(SOURCE_TABLE_FIELDS.length==0) {
                    $.modal.alertError("请添加表字段");
                    return false;
                }
                //查询原表与ods表的公共字段
                $.ajax({
                    url: ctx+"base/etl/table/tableForHosAndOdsFlds",
                    async: false,
                    type: 'POST',
                    dataType: 'json',
                    data: JSON.stringify({"sourFields":SOURCE_TABLE_FIELDS,"tableTar":odsTable,"idDbTar":$("#dwIdDb").val()}),
                    contentType: 'application/json;charset=UTF-8',
                    success: function (result) {
                        var data = result.data;
                        if(data==null || data.length==0) {
                            $.modal.alertError("目标表["+odsTable+"]不存在");
                            return false;
                        }
                        var html="";
                        $.each(data,function (index,item) {
                            html += "<label class=\"checkbox-inline\"><input type=\"checkbox\" checked disabled value=\""+item+"\" >"+item+"</label>";
                        });
                        $("#fldCheckBoxDiv").html(html);
                        var whereType = $("#radiosDiv").find("input:checked").val();
                        if(whereType=="self") {
                            $("#prefixSql").text("delete from "+odsTable+" where "+$("#whereSqlArea").val());
                        } else if(whereType=="dt") {
                            $("#prefixSql").text("delete from "+odsTable+" where "+$("#dtFldSelect").val()+">='${DT_BEGIN}' and "+$("#dtFldSelect").val()+"<'${DT_END}'");
                        } else if(whereType=="all") {
                            $("#prefixSql").text("truncate table "+odsTable) ;
                        }
                    }
                });
            }
            return true;
        } else if(stepDirection == 'forward' && nextStepNumber==2){
            var whereType = $("#radiosDiv").find("input:checked").val();
            var whereSql = $("#whereSqlArea").val();
            var dtFld = $("#dtFldSelect").val();
            if(whereType=="") {
                $.modal.alertError("请选择过滤条件");return ;
            } else if(whereType=="dt") {
                whereSql = dtFld+">='${DT_BEGIN}' and "+dtFld+"<'${DT_END}'";
            }
            var columns = [];
            var coluChecks = $("#fldCheckBoxDiv").find("input");
            if(coluChecks.length==0) {
                $.modal.alertError("缺少字段");return false;
            }
            $.each(coluChecks,function (index,item) {
                columns.push($(this).val());
            });
            var param={"splitPk":$("#splitPk").val(),"tarTableName":$("#tableTar").val(),"tableName":$("#tableSelect").val(),"querySql":$("#qrySql").val(),"euWhereType":whereType,"dtFld":dtFld,"whereSql":whereSql,"beforeSql":$("#prefixSql").val(),"idDbReader":$("#idDb").val(),"columns":columns};
            $.ajax({
                url: ctx+"base/etl/datax/buildJson",
                async: false,
                type: 'POST',
                dataType: 'json',
                data: JSON.stringify(param),
                contentType: 'application/json;charset=UTF-8',
                success: function (result) {
                    if(result.code==0) {
                        var json = JSON.stringify($.parseJSON(result.data),null,2);
                        $("#dataxJson").text(json);
                    } else {
                        $.modal.alertError(result.msg);
                    }
                }
            });
        }
        return true;
    });

    $("#theme-selector").on("change", function() {
        // Change theme
        var options = {
            theme : $(this).val()
        };
        $('#smartwizard').smartWizard("setOptions", options);
        return true;
    });

    $("#reset-btn").on("click", function() {
        // Reset wizard
        $('#smartwizard').smartWizard("reset");
        return true;
    });

    $("#prev-btn").on("click", function() {
        // Navigate previous
        $('#smartwizard').smartWizard("prev");
        return true;
    });

    $("#next-btn").on("click", function() {
        // Navigate next
        $('#smartwizard').smartWizard("next");
        return true;
    });

    $("#form-datax-add").validate({
        focusCleanup: true
    });
    function checkAll(ele) {
        var isChecked = $(ele).is(":checked");
        $("#checkBoxDiv").find("input").attr("checked",isChecked);
    }
    function dbChange() {
        $("#tableSelect").val("");
    }

    function submitHandler() {
        debugger;
        if ($.validate.form()) {
            $.operate.save(prefix + "/add", $('#form-datax-add').serialize());
        }
    }

    $("input[name='dtSysCre']").datetimepicker({
        format: "yyyy-mm-dd",
        minView: "month",
        autoclose: true
    });

    $("input[name='dtSysModi']").datetimepicker({
        format: "yyyy-mm-dd",
        minView: "month",
        autoclose: true
    });
</script>
</body>
</html>